from flask import Flask, request, json, Response, jsonify
import pdb
from model import User, Doc, Spider
from config import db, app
from os import path
from config import APP_ROOT
import hashlib

# https://segmentfault.com/a/1190000003987049
class MyResponse(Response):
    @classmethod
    def force_type(cls, rv, environ=None):
        if isinstance(rv, dict):
            rv = jsonify(rv)
        return super(MyResponse, cls).force_type(rv, environ)

app.response_class = MyResponse

@app.after_request
def after_request(response):
    print("after_request() called: ", response.data)
    return response

@app.route('/')
def hello_world():
    return {'foo': 'bar'}

@app.route('/spiders/<int:id>/change-status', methods= ['POST'])
def set_spiders_status(id):
    spider =  Spider.query.get(id)
    spider.status = not spider.status
    db.session.commit()
    return  {
        'success': True,
        'data': spider.as_dict()
    }

@app.route('/spiders/<int:id>/del', methods= ['POST'])
def del_spider(id):
    spider =  Spider.query.get(id)
    db.session.delete(spider)
    db.session.commit()
    return  {
        'success': True,
        'data': spider.as_dict()
    }

@app.route('/spiders', methods= ['GET', 'POST'])
def get_spiders():
    if request.method == 'POST':
        params = request.get_json(force=True)
        url = params['url']
        target_price = params['target_price']

        spider = Spider(**{'url': url,'target_price': target_price})
        db.session.add(spider)
        db.session.commit()
        return  {
            'success': True,
            'data': spider.as_dict()
        }
    if request.method == 'GET':
        params = request.args
        page = params.get('page', 1)
        spiders = Spider.query.order_by(Spider.created_at.desc()).paginate(int(page), 10, error_out=False)

        data = {
            'success': True,
            'data': [s.as_dict() for s in spiders.items]
        }
        return data

@app.route('/upload', methods= ['GET', 'POST', 'OPTIONS'])
def upload_file():
    resp = Response()
    resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:9100'
    resp.headers['Access-Control-Allow-Credentials'] = 'true'
    if request.method == 'POST':
        f = request.files['file']
        md5 = get_file_md5(f)
        flie_path = path.join(APP_ROOT, 'upload', md5)
        f.seek(0)
        f.save(flie_path)
        resp.data = md5
    return resp

def get_file_md5(f):
    m = hashlib.md5()

    while True:
        data = f.read(10240)
        if not data:
            break

        m.update(data)
    return m.hexdigest()

app.debug = True

if __name__ == '__main__':
    app.run()